package com.yueya.im.service;

import com.yueya.common.base.BaseService;
import com.yueya.common.web.RestResult;
import com.yueya.im.dao.tables.GroupMessage;
import com.yueya.im.dao.tables.PointMessage;
import com.yueya.im.dao.tables.daos.GroupMessageDao;
import com.yueya.im.dao.tables.daos.PointMessageDao;
import com.yueya.im.dao.tables.pojos.GroupMessageDO;
import com.yueya.im.dao.tables.pojos.PointMessageDO;
import com.yueya.im.dto.MsgQueryDto;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Condition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class MessageService extends BaseService {

    @Autowired
    private PointMessageDao pointMessageDao;

    @Autowired
    private GroupMessageDao groupMessageDao;

    @Override
    public List<Condition> getConditions(Object o) {
       return null;
    }
    public List<Condition> getPointMsgConditions(Object o) {
        MsgQueryDto param = (MsgQueryDto)o;
        Condition condition = PointMessage.POINT_MESSAGE.FROM_ID.eq(Long.valueOf(param.getFromId()))
                .and(PointMessage.POINT_MESSAGE.TO_ID.eq(Long.valueOf(param.getToId())));
        if(StringUtils.isNotBlank(param.getMsgId())){
            condition = condition.and(PointMessage.POINT_MESSAGE.MSG_ID.ge(Long.valueOf(param.getMsgId())));
        }
        return Collections.singletonList(condition);
    }

    public List<Condition> getGroupMsgConditions(Object o) {
        MsgQueryDto param = (MsgQueryDto)o;
        Condition condition = GroupMessage.GROUP_MESSAGE.GROUP_ID.eq(Long.valueOf(param.getFromId()));
        if(StringUtils.isNotBlank(param.getMsgId())){
            condition = condition.and(GroupMessage.GROUP_MESSAGE.MSG_ID.ge(Long.valueOf(param.getMsgId())));
        }
        return Collections.singletonList(condition);
    }
    public RestResult pointMsgPage(MsgQueryDto params){
        int offset = (params.getPageNo())*params.getPageSize();
        List<PointMessageDO> list = pointMessageDao.page(offset,params.getPageSize(),getPointMsgConditions(params),PointMessage.POINT_MESSAGE.CREATE_GMT.desc());
        long count  = pointMessageDao.countByCondition(getConditions(params));
        return RestResult.OKWithPage(list,count);
    }
    public RestResult groupMsgPage(MsgQueryDto params){
        int offset = (params.getPageNo())*params.getPageSize();
        List<GroupMessageDO> list = groupMessageDao.page(offset,params.getPageSize(),getGroupMsgConditions(params), GroupMessage.GROUP_MESSAGE.CREATE_GMT.desc());
        long count  = groupMessageDao.countByCondition(getConditions(params));
        return RestResult.OKWithPage(list,count);
    }
}
